<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Libs\System;

class SystemInfoLiunx
{


    /**
     * 获得CPU使用率
     *
     * @return Number
     */
    public function getCpuUsage()
    {
        $fp = popen('top -b -n 2 | grep -E "^(%Cpu|KiB Mem|Tasks)"', "r");//获取某一时刻系统cpu和内存使用情况
        $rs = "";
        while ( ! feof($fp) ) $rs .= fread($fp, 1024);
        pclose($fp);
        $sys_info         = explode("\n", $rs);
        $cpu_info         = explode(",", $sys_info[ 4 ]);  //CPU占有量  数组
        $mem_info         = explode(",", $sys_info[ 5 ]); //内存占有量 数组
        $data[ 'cpu' ]    = (int) trim(trim($cpu_info[ 0 ], '%Cpu(s): '), 'us');  //百分比
        $mem_total        = trim(trim($mem_info[ 0 ], 'KiB Mem :  '), 'total');
        $mem_used         = trim($mem_info[ 2 ], 'used');
        $data[ 'memory' ] = (int) round(100 * intval($mem_used) / intval($mem_total), 2);  //百分比
        //检测时间
        $uptime         = @file_get_contents("/proc/uptime");
        $uptime         = explode(" ", $uptime);
        $data[ 'time' ] = "已运行: " . secToTime($uptime[ 0 ], 'd');
        return $data;
    }
}
